package com.csnf.dao.impl;

import com.csnf.dao.IStudentDao;
import com.csnf.entity.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentDaoImpl implements IStudentDao {
    @Override
    public List<Student> findAll() throws IOException {
        SqlSession sqlSession = getSqlSession();
        List<Student> stuList = sqlSession.selectList("com.csnf.dao.IStudentDao.findAll");
        sqlSession.close();
        return stuList;
    }
    @Override
    public Student findById(Integer id) throws IOException {
        SqlSession sqlSession = getSqlSession();
        Student stu = sqlSession.selectOne("com.csnf.dao.IStudentDao.findById",id);
        sqlSession.close();
        return stu;
    }

    @Override
    public List<Student> findByName(String name) throws IOException {
        SqlSession sqlSession = getSqlSession();
        List<Student> stuList = sqlSession.selectList("com.csnf.dao.IStudentDao.findByName",name);
        sqlSession.close();
        return stuList;
    }

    @Override
    public void deleteById(Integer id) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.delete("com.csnf.dao.IStudentDao.deleteById",id);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void update(Student student) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.update("com.csnf.dao.IStudentDao.update",student);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void insert(Student student) throws IOException {
        SqlSession sqlSession = getSqlSession();
        sqlSession.insert("com.csnf.dao.IStudentDao.insert",student);
        sqlSession.commit();
        sqlSession.close();
    }

    private static SqlSession getSqlSession() throws IOException {
        String path = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(path);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}
